package org.jeecg.modules.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.collections4.CollectionUtils;
import org.jeecg.common.constant.SymbolConstant;
import org.jeecg.common.system.api.entity.SysPermission;
import org.jeecg.common.util.IpUtils;
import org.jeecg.common.util.SpringContextUtils;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.platform.organization.service.ICyPlatformOrganizationPermissionService;
import org.jeecg.modules.role.entity.SysRole;
import org.jeecg.modules.role.entity.SysUserRole;
import org.jeecg.modules.system.entity.SysRolePermission;
import org.jeecg.modules.system.mapper.SysRolePermissionMapper;
import org.jeecg.modules.system.service.ISysRolePermissionService;
import org.jeecg.modules.system.service.ISysRoleService;
import org.jeecg.modules.system.service.ISysUserRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 角色权限表 服务实现类
 * </p>
 *
 * @Author scott
 * @since 2018-12-21
 */
@Service
public class SysRolePermissionServiceImpl extends ServiceImpl<SysRolePermissionMapper, SysRolePermission> implements ISysRolePermissionService {

	@Autowired
	@Lazy
	private ICyPlatformOrganizationPermissionService permissionService;
	@Autowired
	@Lazy
	private ISysRoleService roleService;
	@Autowired
	@Lazy
	private ISysUserRoleService userRoleService;


	@Override
	public void saveRolePermission(String roleId, String permissionIds) {
		String ip = "";
		try {
			//获取request
			HttpServletRequest request = SpringContextUtils.getHttpServletRequest();
			//获取IP地址
			ip = IpUtils.getIpAddr(request);
		} catch (Exception e) {
			ip = "127.0.0.1";
		}
		LambdaQueryWrapper<SysRolePermission> query = new QueryWrapper<SysRolePermission>().lambda().eq(SysRolePermission::getRoleId, roleId);
		this.remove(query);
		List<SysRolePermission> list = new ArrayList<SysRolePermission>();
        String[] arr = permissionIds.split(",");
		for (String p : arr) {
			if(oConvertUtils.isNotEmpty(p)) {
				SysRolePermission rolepms = new SysRolePermission(roleId, p);
				rolepms.setOperateDate(new Date());
				rolepms.setOperateIp(ip);
				list.add(rolepms);
			}
		}
		this.saveBatch(list);
	}

	@Override
	public void saveRolePermission(String roleId, String permissionIds, String lastPermissionIds) {
		String ip = "";
		try {
			//获取request
			HttpServletRequest request = SpringContextUtils.getHttpServletRequest();
			//获取IP地址
			ip = IpUtils.getIpAddr(request);
		} catch (Exception e) {
			ip = "127.0.0.1";
		}
		List<String> add = getDiff(lastPermissionIds,permissionIds);
		if(add!=null && add.size()>0) {
			List<SysRolePermission> list = new ArrayList<SysRolePermission>();
			for (String p : add) {
				if(oConvertUtils.isNotEmpty(p)) {
					SysRolePermission rolepms = new SysRolePermission(roleId, p);
					rolepms.setOperateDate(new Date());
					rolepms.setOperateIp(ip);
					list.add(rolepms);
				}
			}
			this.saveBatch(list);
		}

		List<String> delete = getDiff(permissionIds,lastPermissionIds);
		if(delete!=null && delete.size()>0) {
			for (String permissionId : delete) {
				this.remove(new QueryWrapper<SysRolePermission>().lambda().eq(SysRolePermission::getRoleId, roleId).eq(SysRolePermission::getPermissionId, permissionId));
			}
		}
	}

    @Override
    public void updateRolePermission(String orgId, String approveUser) {
		// 查询权限和角色
	    List<SysPermission> sysPermissions = permissionService.listOrgPermission(orgId);
	    SysRole role = roleService.getOne(new LambdaQueryWrapper<SysRole>()
			    .eq(SysRole::getOrgId, orgId)
			    .eq(SysRole::getRoleCode, "Org_Admin")
			    .eq(SysRole::getRoleName, "管理员")
			    .eq(SysRole::getDescription, "组织管理员")
	    );

	    // 更新角色权限
	    if (role != null) {
		    this.remove(new LambdaQueryWrapper<SysRolePermission>().eq(SysRolePermission::getRoleId, role.getId()));

		    if (CollectionUtils.isNotEmpty(sysPermissions)) {
			    this.saveRolePermission(role.getId(), sysPermissions.stream().map(SysPermission::getId).collect(Collectors.joining(SymbolConstant.COMMA)));
		    }
			//更新管理员角色绑定的id
			userRoleService.update(new LambdaUpdateWrapper<SysUserRole>()
					.eq(SysUserRole::getRoleId,role.getId())
					.set(SysUserRole::getUserId,approveUser));
	    }

    }

    /**
	 * 从diff中找出main中没有的元素
	 * @param main
	 * @param diff
	 * @return
	 */
	private List<String> getDiff(String main,String diff){
		if(oConvertUtils.isEmpty(diff)) {
			return null;
		}
		if(oConvertUtils.isEmpty(main)) {
			return Arrays.asList(diff.split(SymbolConstant.COMMA));
		}

		String[] mainArr = main.split(SymbolConstant.COMMA);
		String[] diffArr = diff.split(SymbolConstant.COMMA);
		Map<String, Integer> map = new HashMap(5);
		for (String string : mainArr) {
			map.put(string, 1);
		}
		List<String> res = new ArrayList<String>();
		for (String key : diffArr) {
			if(oConvertUtils.isNotEmpty(key) && !map.containsKey(key)) {
				res.add(key);
			}
		}
		return res;
	}

}
